package com.weiyuwqj.server.service.debt.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.weiyuwqj.api.common.PageList;
import com.weiyuwqj.api.common.Paginator;
import com.weiyuwqj.api.constant.Constants;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.exception.HfException;
//import com.weiyuwqj.api.hengfeng.model.base.HfBaseResponseBean;
//import com.weiyuwqj.api.hengfeng.model.base.HfDataBean;
//import com.weiyuwqj.api.hengfeng.model.base.HfResultBean;
//import com.weiyuwqj.api.hengfeng.model.platform.HfFundFreezeOrTraw;
import com.weiyuwqj.api.model.*;
import com.weiyuwqj.api.model.vo.BasUserInviteVo;
import com.weiyuwqj.api.model.vo.BusDebtInvestVO;
import com.weiyuwqj.api.model.vo.BusItemInvestVo;
import com.weiyuwqj.api.service.BusDebtInvestService;
import com.weiyuwqj.api.util.DateUtils;
import com.weiyuwqj.api.util.StringUtils;
import com.weiyuwqj.server.mapper.*;
//import com.weiyuwqj.server.pay.PlatformApi;
import com.weiyuwqj.server.service.base.BaseServiceImpl;
import com.weiyuwqj.server.service.invest.module.DebtInvestModule;
import com.weiyuwqj.server.service.sys.module.ConfigTicketModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangyong on 2017/3/22.
 */
@Service("debtInvestService")
public class BusDebtInvestServiceImpl extends BaseServiceImpl<BusDebtInvest> implements BusDebtInvestService{

    @Autowired
    private BusDebtInvestMapper debtInvestMapper;
    @Autowired
    private BusItemInvestMapper itemInvestMapper;

    @Autowired
    private BasDebtMapper debtMapper;

    @Autowired
    private BusUserStatMapper statMapper;

    @Autowired
    private DebtInvestModule investModule;

    @Autowired
    private ConfigTicketModule ticketModule;

    @Autowired
    private BasUserInviteMapper userInviteMapper;

    @Autowired
    private BasCouponMapper couponMapper;

    @Autowired
    private BasUserMapper userMapper;

//    @Autowired
//    private PlatformApi platformApi;

    /**
     * 查询债权投资列表
     * @return
     */
    @Override
    public PageList getDebtInvestList(Paginator p,BusDebtInvest debtInvest) {
        PageHelper.startPage(p.getPageNum(),p.getPageSize());
        List<BusDebtInvestVO> list = debtInvestMapper.getDebtInvestList(debtInvest);
        return new PageList(list);
    }

    /**
     * 根据userId查询可债权的记录
     * @param userId 用户id
     * @return 可债权的记录
     */
    @Override
    public PageList getSupportDebtInvest(Paginator p,Integer userId) {

        //投资记录表
        List<BusItemInvestVo> investList = itemInvestMapper.getCanDebtInvestList(userId);
        //债权记录表
        List<BusDebtInvestVO> debtList = debtInvestMapper.getCanDebtInvestList(userId);
        //将两个list整合成一个list
        List<Map> list = new ArrayList<>();
        for (BusItemInvestVo itemInvestVo:investList){
            Map map=new HashMap();
            map.put("itemName",itemInvestVo.getItemName());

            list.add(map);
        }
        for(BusDebtInvestVO debtInvestVO:debtList){
            Map map=new HashMap();
            map.put("itemName",debtInvestVO.getItemName());

            list.add(map);
        }

        //分页开始
        Integer start = (p.getPageNum()-1)*p.getPageSize();
        Integer end = p.getPageNum()*p.getPageSize()-1;
        if(p.getPageSize()==0){
            p.setPageSize(10);
        }
        if(p.getPageNum()==0){
            p.setPageNum(1);
        }
        Long count=(long)list.size();
        Page result = new Page();
        result.setTotal(count);
        for (int i=start;i<=end && i<list.size();i++){
            result.add(list.get(i));
        }
        p.init(count,list.size(),null);
        PageList pageList = new PageList(result);
        pageList.setPaginator(p);
        //分页结束

        return pageList;
    }

//    /**
//     * 债权投资
//     * @param userId    用户ID
//     * @param amount    投资金额
//     * @param debtId    项目ID
//     * @param couponId  红包ID
//     */
//    @Override
//    public Map doInvest(Integer userId,BigDecimal amount,Integer debtId,Integer couponId, Integer investType){
//        BasDebt debt=debtMapper.selectByPrimaryKey(debtId);
//
//        //判断是否是自己发布的债权
//        if(debt.getUserId().equals(userId)){
//            throw new CrowdException("debt.self_debt_not_invest");
//        }
//
//        String freezeOrderNo = StringUtils.getOrderNo();
//        Map map = investModule.doInvest(userId,amount,debt,couponId,investType);
//
//        //冻结投资人资金(未知红包出款方，还需冻结红包出款方红包资金金额)
//        BasCoupon useCoupon=couponMapper.selectByPrimaryKey(couponId); // 红包
//
//        HfFundFreezeOrTraw freezeOrTraw = new HfFundFreezeOrTraw();
//        if(null!=useCoupon) {
//            freezeOrTraw.setAmount(amount.subtract(useCoupon.getAmount()).toString());
//        }else {
//            freezeOrTraw.setAmount(amount.toString());
//        }
//        freezeOrTraw.setFreeze_flg("01");
//        freezeOrTraw.setPlatcust(userMapper.selectByPrimaryKey(userId).getPlatformId());
//        freezeOrTraw.setRemark(userId+"投资冻结");
//        freezeOrTraw.setOrder_no(freezeOrderNo);
//	    HfResultBean<HfDataBean> result = platformApi.doFundFreeze(freezeOrTraw);
//	    //if (!result.isSuccess()) { // 成功订单数量为0则抛出异常
//	    //   throw new HfException("HfException", result.getMessageText());
//	    //}
//	    String queryId = result.getData().getQuery_id();
//	    Integer debtInvestId = Integer.parseInt(map.get("debtInvestId").toString());
//        debtInvestMapper.updateFreezeOrderNoById(queryId,debtInvestId);
//
//        Map statMap = new HashMap();
//        statMap.put("userId",userId);
//        BusUserStat stat=statMapper.getOneByUserId(statMap);
//
//        if(stat != null && stat.getInvestCount()==0) {
//            // 首次投资个人奖励
//            TicketParamEntity firstInvestParam = new TicketParamEntity();
//            firstInvestParam.setNid(Constants.first_invest_nid);
//            firstInvestParam.setUserId(userId);
//            ticketModule.addTicket(firstInvestParam);
//
//            //首次投资邀请人奖励
//            BasUserInviteVo userInvite = userInviteMapper.getOneByInviteId(userId);
//            if(userInvite !=null){
//                TicketParamEntity firstInvesInvitetParam = new TicketParamEntity();
//                firstInvesInvitetParam.setNid(Constants.first_invite_invest_nid);
//                firstInvesInvitetParam.setUserId(userInvite.getUserId());
//                firstInvesInvitetParam.setAmount(amount);
//                ticketModule.addTicket(firstInvesInvitetParam);
//            }
//        }
//
//        //单笔投资满额奖励
//        TicketParamEntity investParam = new TicketParamEntity();
//        investParam.setNid(Constants.invest_nid);
//        investParam.setUserId(userId);
//        investParam.setAmount(amount);
//        ticketModule.addTicket(investParam);
//
//        //总投资满额奖励
//        TicketParamEntity totalInvestParam = new TicketParamEntity();
//        totalInvestParam.setNid(Constants.total_invest_nid);
//        totalInvestParam.setUserId(userId);
//        ticketModule.addTicket(totalInvestParam);
//
//        return map;
//
//    }

    /**
     * 根据userId查询所有债权记录
     * @param p       分页参数
     * @param userId  用户id
     * @return 所有债权记录
     */
	@Override
	public PageList getAllDebtInvestList(Paginator p, Integer userId) {
        //投资记录表
        List<BusItemInvestVo> investList = itemInvestMapper.getAllDebtInvestList(userId);
        //债权记录表
        List<BusDebtInvestVO> debtList = debtInvestMapper.getAllDebtInvestList(userId);

        //将两个list整合成一个list
        List<Map> list = new ArrayList<>();
        for (BusItemInvestVo itemInvestVo:investList){
            Map map = uniteDebtAndInvest(itemInvestVo.getItemName(),  // 项目名称
                    itemInvestVo.getInvestAmount().toString(),  // 投资金额
                    itemInvestVo.getCollectInterest().toString(), // 应收利息
                    DateUtils.formatDate(itemInvestVo.getAddtime()),   // 投资时间
                    itemInvestVo.getDebtTransferStatus(),  // 投资状态
                    itemInvestVo.getId().toString(), // 投资ID
                    "", // 债券ID
                    itemInvestVo.getItemRate().toString(),//项目利率
                    itemInvestVo.getItemAddRate().toString(),//项目加息利率
                    itemInvestVo.getItemCycle(),// 项目周期
                    itemInvestVo.getItemCycleUnit(),// 周期单位
                    null,null,null
            );
            list.add(map);
        }
        for(BusDebtInvestVO debtInvestVO:debtList){
            Map map = uniteDebtAndInvest(debtInvestVO.getItemName(),  // 项目名称
                    debtInvestVO.getInvestAmount().toString(),  // 投资金额
                    debtInvestVO.getCollectInterest().toString(), // 应收利息
                    DateUtils.formatDate(debtInvestVO.getAddtime()),   // 投资时间
                    debtInvestVO.getStatus(),  // 投资状态
                    "", // 投资ID
                    debtInvestVO.getId().toString(), // 债券ID
                    debtInvestVO.getItemRate().toString(),//项目利率
                    debtInvestVO.getItemAddRate().toString(),//项目加息利率
                    debtInvestVO.getItemCycle(),// 项目周期
                    debtInvestVO.getItemCycleUnit(),// 周期单位
                    debtInvestVO.getDebtType().toString(),
                    debtInvestVO.getFee().toString(),
                    debtInvestVO.getRestPeriods().toString()
            );
            list.add(map);
        }

        //分页开始
        Integer start = (p.getPageNum()-1)*p.getPageSize();
        Integer end = p.getPageNum()*p.getPageSize()-1;
        if(p.getPageSize()==0){
            p.setPageSize(10);
        }
        if(p.getPageNum()==0){
            p.setPageNum(1);
        }
        Long count=(long)list.size();
        Page result = new Page();
        result.setTotal(count);
        for (int i=start;i<=end && i<list.size();i++){
            result.add(list.get(i));
        }
        p.init(count,list.size(),null);
        PageList pageList = new PageList(result);
        pageList.setPaginator(p);
        //分页结束

        return pageList;
	}


    /**
     * 合并债转和投资列表
     * @param itemName 项目名称
     * @param investAmount 投资金额
     * @param collectInterest 应收利息
     * @param addtime 投资时间
     * @param status 状态
     * @param investId 投资ID
     * @param debtId 债权ID
     * @param itemRate 项目利率
     * @param itemAddRate 项目加息利率
     * @param itemCycle 项目周期
     * @param itemCycleUnit 项目周期单位
     * @return 债转和投资列表
     * */
    private Map uniteDebtAndInvest(String itemName, String investAmount, String collectInterest, String addtime, Integer status, String investId,
                                   String debtId, String itemRate, String itemAddRate, Integer itemCycle, Integer itemCycleUnit,
                                   String debtType,String fee,String restPeriods) {
        Map map = new HashMap();
        map.put("itemName",itemName); // 项目名称
        map.put("investAmount", investAmount); // 投资金额
        map.put("collectInterest", collectInterest); // 应收利息
        map.put("addtime", addtime); // 投资时间
        map.put("status",status); // 状态
        map.put("investId", investId); // ID
        map.put("debtId", debtId); // ID
        map.put("itemRate", itemRate); // 项目利率
        map.put("itemAddRate", itemAddRate); // 项目加息利率
        map.put("itemCycle", itemCycle); // 项目周期
        map.put("itemCycleUnit", itemCycleUnit); // 项目周期单位
        map.put("debtType", debtType); // 类型
        map.put("fee", fee); // 服务费
        map.put("restPeriods", restPeriods); // 剩余期数
        return map;
    }

}
